<?php

namespace app\admin\controller\polite;

use app\admin\model\PoliteComprehensive;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\service\CommonService;
use think\App;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\annotation\ControllerAnnotation;
use think\facade\Db;
use function GuzzleHttp\default_user_agent;

/**
 * Class Goods
 * @package app\admin\controller\polite
 * @ControllerAnnotation(title="乐购乡镇管理")
 */
class PolitePay extends AdminController
{

    use Curd;

    protected $relationSearch = false;
    protected $searchCategory;
    protected $category = 3;
    protected $categoryType = '乐购乡镇分类';
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new PoliteComprehensive();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $admin=session('admin');
            if($admin['type']==3){
                //乡镇管理员，显示自己乡镇的数据
                $where[]=['township','=',$admin['area_id']];
            }
            $where[] = ['category','=',$this->category];
            $count = $this->model->where($where)->count();
            $list = $this->model->where($where)->page($page, $limit)->order($this->sort)->select();
            foreach ($list as $k=>$v){
                $list[$k]=$this->resetInfo($v);
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add($id = null)
    {
        $typeArr = (new \app\admin\service\PoliteConfigService())->getConfigByTypeName($this->categoryType);
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $types = $this->request->post('type', []);
            $post['type'] = implode(',', array_keys($types));
            $rule = [
                'name|名称'   => 'require',
                'type|分类'  => 'require',
                'start_time|营业开始时间'  => 'require',
                'end_time|营业结束时间'  => 'require',
                'contact_phone|联系电话'  => 'require',
                'addr_name|位置名称'  => 'require',
                'addr_text|详细地址'  => 'require',
                'longitude|经度'  => 'require',
                'latitude|纬度'  => 'require',
                'score|评分'  => 'require',
                'files|轮播图'  => 'require',
                'description|描述'  => 'require',
                'content|简介'  => 'require',
            ];
            $this->validate($post, $rule);

            $score = $post['score'];
            if ($score > 5){
                $this->error('评分不可超过5分');
            }
            $files = explode('|',$post['files']);
            if (count($files) > 10){
                $this->error('轮播图片最多不超过10张');
            }

            $post['township']=$this->admin['area_id'];
            $post['category']=$this->category;
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign([
            'typeArr'=>$typeArr,
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $row=$this->resetInfo($row);
        $typeArr = (new \app\admin\service\PoliteConfigService())->getConfigByTypeName($this->categoryType);
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $types = $this->request->post('type', []);
            $post['type'] = implode(',', array_keys($types));
            $rule = [
                'name|名称'   => 'require',
                'type|分类'  => 'require',
                'start_time|营业开始时间'  => 'require',
                'end_time|营业结束时间'  => 'require',
                'contact_phone|联系电话'  => 'require',
                'addr_name|位置名称'  => 'require',
                'addr_text|详细地址'  => 'require',
                'longitude|经度'  => 'require',
                'latitude|纬度'  => 'require',
                'score|评分'  => 'require',
                'files|轮播图'  => 'require',
                'description|描述'  => 'require',
                'content|简介'  => 'require',
            ];
            $this->validate($post, $rule);

            $score = $post['score'];
            if ($score > 5){
                $this->error('评分不可超过5分');
            }
            $files = explode('|',$post['files']);
            if (count($files) > 10){
                $this->error('轮播图片最多不超过10张');
            }

            $post['township']=$this->admin['area_id'];
            $post['category']=$this->category;
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }else{
            $row['type'] = explode(',',$row['type']);

            $this->assign([
                'typeArr'=>$typeArr,
            ]);
        }
        $this->assign([
            'id'          => $id,
            'row'         => $row,
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    private function resetInfo($data){
        if($data){
            if(!empty($data['township']))$data['township_text']=$this->getArea($data['township'])['name'];
            $data['type_text'] = '';
            if(!empty($data['type']) && !empty($data['category'])){
                $configTypeName = CommonService::getPoliteComprehensiveType()[$data['category']];
                $typeArr = explode(',',$data['type']);
                $typeNameList = (new \app\admin\service\PoliteConfigService)->getConfigByTypeName($configTypeName,[['id','in',$typeArr]]);
                if (!empty($typeNameList)) $data['type_text'] = implode(' | ',array_column($typeNameList,'config_value'));
            }
            $data['is_recommend_text'] = $data['is_recommend'] == 1 ? '是' : '否';
        }
        return $data;
    }
}